<script setup lang="ts">
import { ref } from 'vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Point from '@arcgis/core/geometry/Point'
import { onMounted } from 'vue'
import { IonPage, IonButton, alertController, useIonRouter } from '@ionic/vue'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { Geolocation } from '@capacitor/geolocation'
import { BarcodeScanner } from '@capacitor-community/barcode-scanner'
import request from '@/utils/request'
import { baseResponse } from '@/types/public'
import { useUserStore } from '@/stores'

// 创建一个用于显示 alert 的函数
async function showAlert(message: string) {
  const alert = await alertController.create({
    header: '提示',
    message: message,
    buttons: ['确认'],
  })
  await alert.present()
}

//初始化地图容器
const mapViewContainer = ref<HTMLDivElement>()
const nullContainer = ref<HTMLDivElement>()

//添加要素图层
const campusLayer = new FeatureLayer({
  url: 'https://services7.arcgis.com/p26KIN0Hov5c0MG9/arcgis/rest/services/Attendance/FeatureServer/0',
  outFields: ['*'],
})

//初始化地图
const map = new Map({
  // basemap styles service
  basemap: {
    baseLayers: [gaodeLayer],
  },
  layers: [campusLayer],
})

//初始化mapview
const view = new MapView({
  map: map,
  center: [116.7963581069489, 36.53729500053177], // Longitude, latitude
  zoom: 13, // Zoom level
})

//待dom元素完成后加入
onMounted(async () => {
  view.container = mapViewContainer.value!
  view.ui.add('signInButton', 'top-right')
  view.ui.add('logoutButton', 'bottom-right')
})

// 退出登录
const userStore = useUserStore()
const ionRouter = useIonRouter()

const logout = async () => {
  userStore.removeToken()
  await showAlert('退出登录成功')
  ionRouter.replace('/login')
}

// 检查Google Play Services
async function checkGooglePlayServices() {
  try {
    // 尝试获取位置，如果成功，说明Google Play Services正常
    await Geolocation.getCurrentPosition({
      enableHighAccuracy: false,
      timeout: 5000,
    })
    return true
  } catch (error: any) {
    if (error.message && error.message.includes('Google Play Services')) {
      return false
    }
    // 其他错误不是Google Play Services的问题
    return true
  }
}

// 签到
const SignIn = async () => {
  try {
    // 首先检查Google Play Services
    const isGooglePlayServicesAvailable = await checkGooglePlayServices()
    if (!isGooglePlayServicesAvailable) {
      await showAlert('Google Play Services错误：请确保您的设备已安装最新版本的Google Play Services，并且已开启位置服务。')
      return
    }

    await showAlert('开始扫码签到')
    // 扫码获取签到连接
    const status = await BarcodeScanner.checkPermission({ force: true })
    if (!status.granted) {
      return
    }

    // 开始扫描
    document.querySelector('body')!.style.background = 'transparent'
    view.container = nullContainer.value!
    BarcodeScanner.hideBackground()
    const scannerResult = await BarcodeScanner.startScan()
    document.querySelector('body')!.style.background = ''
    BarcodeScanner.stopScan()
    BarcodeScanner.showBackground()
    view.container = mapViewContainer.value!

    if (scannerResult.hasContent) {
      await showAlert('扫码成功')
    } else {
      await showAlert('扫码失败，未获取到内容')
      return
    }

    // 获取位置信息
    try {
      const position = await Geolocation.getCurrentPosition({
        enableHighAccuracy: true,
        timeout: 150000,
        maximumAge: 0,
      })

      const point = new Point({
        longitude: position.coords.longitude,
        latitude: position.coords.latitude,
      })

      // 查询是否在签到范围内
      const query = campusLayer.createQuery()
      query.geometry = point
      query.spatialRelationship = 'intersects'
      query.outFields = ['*']

      const queryResult = await campusLayer.queryFeatures(query)
      console.log('查询结果:', queryResult)

      if (queryResult.features.length === 0) {
        await showAlert('不在签到范围内')
        return
      }

      // 处理签到
      for (const feature of queryResult.features) {
        const objectId = feature.attributes['OBJECTID'] as number
        const httpUrl = scannerResult.content + `&layerId=${objectId}`
        request.defaults.baseURL = ''

        try {
          const httpResult = await request.get<baseResponse<boolean>>(httpUrl)
          if (httpResult.data.data === true) {
            await showAlert('签到成功')
          } else {
            await showAlert('签到失败')
          }
        } catch (httpError: any) {
          console.error('HTTP请求错误:', httpError)
          await showAlert('签到请求失败: ' + (httpError.message || '未知错误'))
        }
      }

    } catch (locationError: any) {
      console.error('位置获取错误:', locationError)
      if (locationError.message && locationError.message.includes('Google Play Services')) {
        await showAlert('Google Play Services错误：请确保您的设备已安装最新版本的Google Play Services，并且已开启位置服务。')
      } else {
        await showAlert('获取位置信息失败：' + (locationError.message || '未知错误'))
      }
    }

  } catch (error: any) {
    console.error('签到过程错误:', error)
    await showAlert('签到过程出错: ' + (error.message || '未知错误'))
  }
}
</script>
<template>
  <ion-page>
    <div id="mapViewContainer" ref="mapViewContainer" class="mapView"></div>
    <ion-button @click="SignIn" id="signInButton">签到</ion-button>
    <ion-button @click="logout" id="logoutButton" color="danger">退出登录</ion-button>
  </ion-page>
</template>

<style scoped>
.mapView {
  width: 100%;
  height: 100%;
}

#logoutButton {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}
</style>
